package com.chinacoal.microservice.impl.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.toolkit.StringUtils;
import com.chinacoal.microservice.api.OrgEmpClient;
import com.chinacoal.microservice.exception.MessageException;
import com.chinacoal.microservice.impl.mapper.RestSysMapper;
import com.chinacoal.microservice.impl.service.ApproverService;
import com.chinacoal.microservice.impl.service.DockingUrlService;
import com.chinacoal.microservice.model.organization.OrgOrganization;
import com.chinacoal.microservice.model.wofkflow.entity.DockingUrlEntity;
import com.chinacoal.microservice.model.wofkflow.resource.WorkflowVar;
import com.chinacoal.microservice.util.result.Result;
import com.chinacoal.microservice.util.tool.Tool;

/**  
 * @Package: com.chinacoal.microservice.impl.service.impl.ApproverServiceImpl
 * @ClassName: ApproverServiceImpl
 * @ClassDesc: 流程审批人ServiceImpl
 * @Createby: sunh
 * @CreatedDate: 2019-12-02 10:40:09
 */  
@Service
public class ApproverServiceImpl implements ApproverService {

	@Resource
	private DockingUrlService dockingUrlService;
	@Resource
	private OrgEmpClient orgEmpClient;
	@Resource
	private RestSysMapper restSysMapper;
	
	@Override
	public List<Map<String, String>> getApprover(Map<String, String> param) throws Exception{

		List<Map<String, String>> approverList = new ArrayList<Map<String,String>>();
		
		/* 系统编码 */
		String sysCode =  param.get("sysCode");
		/* 审批人计算类型 */
		String type = param.get("type");
		/* 流程提交人 */
		String submitUser = param.get("submitter");
		/* 参数列表 */
		String paramList = param.get("paramList");
		/* 实例id */
		String insId = param.get("insId");
		
		// 参数校验
		if(StringUtils.isEmpty(sysCode)) throw new MessageException("参数有误，系统编码不能为空");
		
		// 获取对接系统地址
		DockingUrlEntity dockingUrlEntity = dockingUrlService.selectById(sysCode);
		if(dockingUrlEntity == null || StringUtils.isEmpty(dockingUrlEntity.getCustomUrl1())) {
			throw new MessageException("获取不到对接系统的地址");
		}
		
		// 执行计算并获取审批人
		if(StringUtils.isEmpty(type) || WorkflowVar.APPROVER_TYPE_1.equals(type)) {
			
			approverList = approvalCustom(dockingUrlEntity, insId, paramList, submitUser);
		}else if(WorkflowVar.APPROVER_TYPE_2.equals(type)) {
			if(StringUtils.isEmpty(paramList)) throw new MessageException("获取审批人等级参数");
			int approverLevel = Integer.parseInt(paramList.split("\\.")[0]);
			approverList = approvalStepByStepByOrg(dockingUrlEntity, approverLevel, submitUser, dockingUrlEntity.getParam2());
		}else {
			
		}
		
		return approverList;
	}

	/**  
	 * @Package: com.chinacoal.microservice.impl.service.impl.ApproverServiceImpl.approvalCustom
	 * @MethodName: approvalCustom
	 * @MethodDesc: 自定义审批人
	 * @ParamList: {
	 *				 @param url
	 *				 @param insId
	 *				 @param paramList
	 *				 @param submitUser
	 *			   }
	 * @Return: List<Map<String,String>>
	 * @Createby: sunh
	 * @CreatedDate: 2019-12-02 10:39:44
	 */ 
	private List<Map<String, String>> approvalCustom(DockingUrlEntity dockingUrlEntity, String insId, String paramList, String submitUser) throws Exception{

		List<Map<String, String>> approverList = new ArrayList<Map<String,String>>();
		
		Map<String,Object> param = new HashMap<String, Object>();
		param.put("insId", insId);
		param.put("submitUser", submitUser);
		param.put("params", paramList);
		
		String url = dockingUrlEntity.getCustomUrl1();
		Result<List<Map<String, String>>> result = Tool.invokeInterfaceRest(url, param, null, HttpMethod.POST, new ParameterizedTypeReference<Result<List<Map<String, String>>>>() {});
		
		if(result.getCode() != 10000) {
			throw new Exception(result.getMsg());
		}else {
			approverList = result.getData();
		}
		
		return approverList; 
	}
	
	/**  
	 * @Package: com.chinacoal.microservice.impl.service.impl.ApproverServiceImpl.approvalStepByStepByOrg
	 * @MethodName: approvalStepByStepByOrg
	 * @MethodDesc: 
	 * @ParamList: {
	 *				 @param url
	 *				 @param approverLevel
	 *				 @param submitUser
	 *			   }
	 * @Return: List<Map<String,String>>
	 * @Createby: sunh
	 * @CreatedDate: 2019-12-02 10:39:06
	 */ 
	private List<Map<String, String>> approvalStepByStepByOrg(DockingUrlEntity dockingUrlEntity, Integer approverLevel, String submitUser, String rootOrgCode) throws Exception{
		
		List<Map<String, String>> approverList = new ArrayList<Map<String,String>>();
		
		// 根据提交人获取组织信息
		Integer approverOrgId = null;
		// Result<List<OrgOrganization>>  orgResult = orgEmpClient.getOrgByEmpId(Tool.toInteger(submitUser));
		
		OrgOrganization rootOrg = restSysMapper.getOrgIdByOrgCode(rootOrgCode);
		if(rootOrg == null ) throw new Exception("未查询到组织，rootOrgCode:" + rootOrgCode);
		
		// 计算当前审批的组织层级
		Integer rootOrgId = Tool.toInteger(rootOrg.getOrgId().toString());
		List<OrgOrganization> orgList = restSysMapper.getOrgByEmpId(Tool.toInteger(submitUser), rootOrgId);
		if(orgList == null || orgList.size() != 1) {
			throw new Exception("提交人的组织或部门未获取到或获取到多个，无法确定审批人");
		}
		OrgOrganization orgOrganization = orgList.get(0);
		// 获取到公司层级
		String[] orgLevel = orgOrganization.getOrgSeq().split("\\.");
		// 去除虚拟组织和空
		approverLevel = approverLevel + 1;
		// 获取审批人的组织id
		approverOrgId = Integer.parseInt(orgLevel[approverLevel]);
		
		// 调用接口获取人员数据
		String url = dockingUrlEntity.getCustomUrl1() + "?orgId=" + approverOrgId;
		
		Map<String, String> headers = new HashMap<String, String>();
		headers.put("X-EOS-SourceSysKey", dockingUrlEntity.getParam1());
		
		Result<List<Map<String, String>>> result = Tool.invokeInterfaceRest(url, null, headers, HttpMethod.GET, new ParameterizedTypeReference<Result<List<Map<String, String>>>>() {});
		
		if(result.getCode() != 0) {
			throw new Exception(result.getMsg());
		}else {
			approverList = result.getData();
		}
		
		return approverList;
	}
}
